<?php
$host = '0.0.0.0';
$port = 6666;
$listen_socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
socket_set_option( $listen_socket, SOL_SOCKET, SO_REUSEADDR, 1 );
socket_set_option( $listen_socket, SOL_SOCKET, SO_REUSEPORT, 1 );
socket_bind( $listen_socket, $host, $port );
socket_listen( $listen_socket );
socket_set_nonblock( $listen_socket );
$client_arr = array();
$event_arr  = array();
$client_arr[ intval( $listen_socket ) ] = $listen_socket;
function ev_write( $event_buffer_event, $connect_socket ) {
    global $client_arr;
    global $event_arr;
    echo "ev_write callback".PHP_EOL;
    // 下面这行代码先注释掉...
    // $event_buffer_event->write( "hi".PHP_EOL );
    // 首先是生产环境，一定不能加这句...不然会死的很惨烈
    // 其次是测试研究阶段，建议加上，不然配置低的也可能会死的很惨烈
    sleep( 1 );
}
function ev_accept( $listen_socket, $what, $event_base ) {
    global $client_arr;
    global $event_arr;
    // accept后，listen-socket上的可读事件将会被清空
    $connect_socket = socket_accept( $listen_socket );
    socket_set_nonblock( $connect_socket );
    if ( !$connect_socket ) {
        return;
    }
    $client_event = new EventBufferEvent( $event_base, $connect_socket, EventBufferEvent::OPT_DEFER_CALLBACKS );
    $client_event->setCallbacks( NULL, 'ev_write', NULL, $connect_socket );
    $client_event->setTimeouts( 30, 2 );
    $client_event->setWatermark( Event::WRITE, 0, 4 );
    $client_event->enable( Event::WRITE );
    $client_arr[ intval( $connect_socket ) ] = $connect_socket;
    $event_arr[ intval( $connect_socket ) ]  = $client_event;
}

$event_config = new EventConfig();
$event_base   = new EventBase( $event_config );
$event = new Event( $event_base, $listen_socket, Event::READ | Event::PERSIST, 'ev_accept', $event_base );
$event->add();
$event_base->loop();